import {
  //  getPreviewDetail, 
  getPrettifyFromUri
} from "@Api/productApi"
import { upDataImageNewApi } from "@Api/shopsApi"
import { getPreviewDetail } from "@Api/sysApi/productApi"
import { getJiebaApi, getSearchWordApi } from "@Api/toolsApi"
import {
  message
} from "@bytedance/mona-ui"
import md5 from "md5";
// import { upFileToOss } from '@Utils/getPageDecrypt'
import { store } from "~store"

import { uploadMaterialApi, getProductUpdateRule } from "@Api/sysApi/productApi"
import { queryMaterialDetailApi } from "@Api/sysApi/materialApi"
export async function getGoodsDetells(goodis) {
  const res = await getPreviewDetail(goodis)
  return res
}

export async function getPrettifyFromUriData(data) {
  const res = await getPrettifyFromUri(data)
  return res
}

export async function getJiebaApiData(title) {
  const data = await getJiebaApi(title)
  return data
}

export async function getSearchWordApiData(data) {
  const res = await getSearchWordApi(data)
  return res
}



// Tools方法
export function getObjectURL(file) {
  let url
  if (window["createObjectURL"] != undefined) {
    // basic
    url = window["createObjectURL"](file)
  } else if (window.URL != undefined) {
    // mozilla(firefox)
    url = window.URL.createObjectURL(file)
  } else if (window.webkitURL != undefined) {
    // webkit or chrome
    url = window.webkitURL.createObjectURL(file)
  }
  return url
}

// 洗牌
export function shuffleArray(array) {
  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]];
  }
  return array;
}

// 返回处理后的图片数据提供上传使用

export async function setImageInfoDtatFun(setImages, copyGoodConfig, type, stopCb, isshuffle = false) {
  // console.log('copyNum',setImageData, copyGoodConfig, type)
  // console.log('收到的信息', setImages, copyGoodConfig, type)
  // return
  const {
    copynum,
    goodImageCf,
    goodDetelesImageCf,
    goodImage34Cf
  } = copyGoodConfig
  if (type === 3 && goodImage34Cf == 1) {
    return false
  }
  if (!setImages || !setImages.length || Array.isArray(setImages) === false) {
    message.error('请正确选择图片')
    throw new Error("图片数据格式错误");
  }
  const setImageData = JSON.parse(JSON.stringify(setImages))
  // 补齐图片组数量

  let cherType = 0
  // let isshuffle = true // 是否打乱顺序

  if (type === 1) {
    cherType = goodImageCf
  }
  if (type === 2) {
    cherType = goodDetelesImageCf
  }
  if (type === 3) {
    cherType = goodImage34Cf
  }
  if (type === 4) {
    cherType = 2
  }
  stopCb(2)
  // 如果是详情图 在没有上传组的情况 需要对图片进行拼接后再裁减 **** 重要

  // if (cherType === 2) { // 在是修改图片的情况下调用
  //   // 这里补齐数量并后面的图片随机打乱

  // }
  // if(cherType === 1) {
  //   console.log('默认', setImages)
  // }
  return setImageContentFunc(cherType)
  async function setImageContentFunc(cherTypeIn) {
    // 默认情况打乱所有的图片
    const terImages = cherTypeIn === 2 ? copynum - setImageData.length : copynum
    const copyImageDatas = cherTypeIn === 2 ? JSON.parse(JSON.stringify(setImageData)) : []
    if (terImages > 0) {
      for (let i = 0; i < terImages; i++) {
        const miyer: number = Math.floor(Math.random() * setImageData.length)
        const copLiter = JSON.parse(JSON.stringify(setImageData[miyer]))
        if (isshuffle && type !== 3) {
          // 是详情图的话需要进行拼接裁剪
          copLiter.list = shuffleArray(JSON.parse(JSON.stringify(copLiter.list)))
        }
        copyImageDatas.push(copLiter)
      }
    }
    stopCb(10)
    // console.log('copyImageDatas', copyImageDatas)
    // console.log('打乱顺序后图片组', copyImageDatas[0].list[0].url)

    // 为生成的图片组做后续处理
    // 无论是否需要合成都需要做一个加蒙层且去除随机像素点
    // 决定对图片像素进行操作使得图片不同
    // 这里需要对图片进行操作
    const getadats = await setImageReload(copyImageDatas, cherTypeIn)
    // console.log('getadats000', getadats)
    // return
    stopCb(70)
    // 这里可以扣进度32
    // console.log('getadats', getadats)
    // return
    // 上传到oss
    /** 修改为直接上传⬇️⬇️⬇️⬇️⬇️⬇️⬇️ */
    const upBefroDaterNewData = await upBefroDaterNew(getadats)
    // console.log('upBefroDaterNewData', upBefroDaterNewData)
    let upimga: any = []
    upBefroDaterNewData.forEach(res => {
      // console.log('res', res)
      // upimga.push([])
      const upumgse: any = []
      res.forEach((item: any) => {
        // console.log('item', item)
        if (item.isNoupLoads) {
          upumgse.push({ byte_url: item.url })
        } else if (item.code === 0) {
          upumgse.push({ byte_url: item.data[0] })
        }

      })
      upimga.push(upumgse)
    })
    return upimga
    /** 修改为直接上传⬆️⬆️⬆️⬆️⬆️⬆️⬆️ */
    const upImageFunlter = await upBefroDater(getadats)
    stopCb(62)
    // console.log('upImageFunlter', upImageFunlter)
    // return
    // 上传到抖店素材库
    const upListData: any = []
    const addUpSetDataArr = []
    const upConternMoters = upImageFunlter.map((res, i) => {
      let upImages = []
      let noUdata = []
      const upImgad = res.map((item, index) => {
        if (item.isNoupLoads) {
          // return {
          //   isNoupLoads: true,
          //   path: item.url,
          //   aaaaaa: item.url
          // }
          noUdata.push({
            isNoupLoads: true,
            byte_url: item.url,
            index
            // aaaaaa: item.url
          })
          return {
            isNoupLoads: true,
            byte_url: item.url,
            index
          }
        }
        const names = item.name.split('/')
        upImages.push({
          request_id: names[names.length - 1].split('.')[0],
          filename: names[names.length - 1],
          path: item.url
        })
        return {
          request_id: names[names.length - 1].split('.')[0],
          filename: names[names.length - 1],
          path: item.url
        }
        // {
        //   request_id: names[names.length - 1].split('.')[0],
        //   filename: names[names.length - 1],
        //   path: item.url
        // }
      })
      upListData.push(upImgad)

      if (upImages.length) {
        addUpSetDataArr.push(uploadMaterialApi(upImages))
      }
      if (noUdata.length) {
        return noUdata
      }
      // return noUdata.length ? noUdata : uploadMaterialApi(upImages)
      // let upImgaeda = []
      // upImgad.map(upimagedauter => {
      //   if(upimagedauter.isNoupLoads) {
      //     return Promise.resolve(upimagedauter)
      //   }
      //   upImgaeda.push()
      //   // return uploadMaterialApi(upImgad)
      // })

    })
    // 并发上传到抖店素材库
    const noUpdata = await Promise.all(upConternMoters)
    stopCb(67)
    const getOssPutDouDian = await Promise.all(addUpSetDataArr)
    stopCb(82)
    // console.log('getOssPutDouDian', getOssPutDouDian)
    // console.log('noUpdata', noUpdata)

    const getDater = await asycGetImageStatus(getOssPutDouDian)
    stopCb(93)
    // console.log('getDater', getDater)
    const ImageEndFeindlie = []
    getDater.forEach(cher => {
      ImageEndFeindlie.push(...cher)
    })
    let outInter: any = []
    upListData.forEach((res, index) => {
      let addInfor: any = []
      res.forEach(item => {
        if (item.isNoupLoads) {
          addInfor.push(item)
          return
        }

        const findFeil = ImageEndFeindlie.find((titel) => {
          return item.filename === titel.materil_name
        })
        addInfor.push(findFeil)
      })
      outInter.push(addInfor)

    })
    // console.log('outInter00123', outInter)
    return outInter
    // console.log('getDatergetDater', getDater, upListData, noUpdata)
    // return { getOssPutDouDian, upListData }
  }

}

export async function asycGetImageStatus(ImageList) {
  // console.log('ImageList', ImageList)
  // let getIdList = []
  const gtProAll = ImageList.map((res, i) => {
    return new Promise(async (resolves, rejects) => {
      if (res.code === 10000) {
        const getLiteryurt = Object.keys(res.data.success_map).map((item) => {
          return new Promise((resolve, reject) => {
            queryMaterialDetailApi(res.data.success_map[item].MaterialId).then((itemimg => {
              // console.log('itemimg', itemimg)
              if (itemimg.code === 10000 && itemimg.data.material_info.audit_status === 3) {
                resolve(itemimg.data.material_info)
              } else if (itemimg.data.material_info.audit_status !== 4) {
                setTimeout(() => {
                  queryMaterialDetailApi(res.data.success_map[item].MaterialId).then((itemimg) => {
                    if (itemimg.code === 10000 && itemimg.data.material_info.audit_status === 3) {
                      resolve(itemimg.data.material_info)
                    }
                  })
                }, 3000)
              }
            }))
          })
        })
        const getData = await Promise.all(getLiteryurt)
        // console.log('getData234', getData)
        resolves(getData)
        // gtProAll.push(getLiteryurt)
        // return getData
      }

    })

  })
  const getIdList = await Promise.all(gtProAll)
  // let outInter: any = []
  // upImgad.forEach((res, index) => {
  //   let addInfor: any = []
  //   res.forEach(item => {
  //     const findFeil = getIdList[index].find((titel) => {
  //       return item.filename === titel.materil_name
  //     })
  //     addInfor.push(findFeil)
  //   })
  //   outInter.push(addInfor)

  // })
  return getIdList
}

async function setImageReload(setImages, cherTypeIn) {
  // const setImageData = JSON.parse(JSON.stringify(setImages))
  const picImagesData = JSON.parse(JSON.stringify(setImages))
  // console.log('picImagesDat000a', picImagesData)
  // return
  let getdataConternt: any = []
  picImagesData.forEach((res) => {
    // console.log('res', res)
    res.list.forEach((item) => {
      // console.log('item', item)
      getdataConternt.push(getImageMeager(item))
    })
  })
  // console.log('getdataConternt', getdataConternt[0])
  await Promise.all(getdataConternt)

  return picImagesData



  async function getImageMeager(orderData) {
    let imagetype = 'image/jpeg'
    const ister = await isTransparentImage(orderData.url)
    if (ister) {
      imagetype = 'image/png'
    }
    // console.log('ister', ister)
    return new Promise((resolve, reject) => {
      // console.log('orderData++++', orderData)
      let lodinImagelist: any = []
      let img
      let whimg

      // console.log('orderData', orderData)
      // console.log('is34', orderData.is34)
      // console.log('isSku', orderData.isSku)
      if (orderData.watermark.url && !orderData.watermark.url.startsWith('blob:')) {
        orderData.watermark.url = orderData.watermark.url // + '?time=' + new Date().valueOf()
      }
      if (orderData.is34 || orderData.isSku) {
        if (orderData.url && orderData.watermark.url) {
          img = new Image()
          img.setAttribute("crossOrigin", "Anonymous")
          img.src = orderData.url // + '?time=' + new Date().valueOf()
          whimg = new Image()
          whimg.setAttribute("crossOrigin", "Anonymous")
          whimg.src = orderData.watermark.url
          lodinImagelist = [new Promise((resolvea) => {
            img.onload = resolvea
          }), new Promise((resolvea) => {
            whimg.onload = resolvea
          })]
          Promise.all(lodinImagelist).then(() => {
            let canvas = document.createElement("canvas")
            let context: any = canvas.getContext("2d")
            canvas.width = orderData.is34 ? 750 : orderData.isSku ? 800 : 800
            canvas.height = orderData.is34 ? 1000 : orderData.isSku ? 800 : 800
            context.drawImage(img, 0, 0, canvas.width, canvas.height)
            // 存在即合并
            if (orderData.watermark.url) {
              const wb = canvas.width / 100
              const hb = canvas.height / (orderData.is34 ? 133.333333 : orderData.isSku ? 100 : 100)
              // 图标会变形问题
              // 将第二张图片绘制到右侧位置
              context.drawImage(
                whimg,
                wb * orderData.watermark.left,
                hb * orderData.watermark.top,
                wb * orderData.watermark.width,
                hb * orderData.watermark.height
              )
            }
            // 对图片微调像素
            // let canvas2 = document.createElement("canvas")
            // canvas2.width = canvas.width;
            // canvas2.height = canvas.height;
            // let ctx2: any = canvas2.getContext("2d");
            // let imageData = context.getImageData(0, 0, canvas.width, canvas.height);
            // let imgData2 = dealImageData(imageData);
            // ctx2.putImageData(imgData2, 0, 0);
            // orderData.mergeurl = canvas.toDataURL("image/jpeg", 1)
            // console.log('orderData.mergeurl ', orderData.mergeurl)
            let canvas2 = document.createElement("canvas")
            canvas2.width = canvas.width;
            canvas2.height = canvas.height;
            let ctx2: any = canvas2.getContext("2d");
            let imageData = context.getImageData(0, 0, canvas.width, canvas.height);
            let imgData2 = dealImageData(imageData);
            ctx2.putImageData(imgData2, 0, 0);
            orderData.mergeurl = canvas2.toDataURL(imagetype, 1)
            resolve(orderData)

          })
          return
        }
        if (orderData.url) {
          orderData.mergeurl = orderData.url
          orderData.isNoSet = true
          resolve(orderData)
          // console.log('只有原图 直接返回不用上传')
          return
        }
        if (orderData.watermark.url) {

          whimg = new Image()
          whimg.setAttribute("crossOrigin", "Anonymous")
          whimg.src = orderData.watermark.url
          whimg.onload = () => {
            let canvas = document.createElement("canvas")
            let context: any = canvas.getContext("2d")
            canvas.width = orderData.is34 ? 750 : orderData.isSku ? 800 : 800
            canvas.height = orderData.is34 ? 1000 : orderData.isSku ? 800 : 800
            context.fillStyle = "#fff"; // 设置填充颜色为红色
            context.fillRect(0, 0, canvas.width, canvas.height)
            // context.drawImage(whimg, 0, 0, canvas.width, canvas.height)
            const wb = canvas.width / 100
            const hb = canvas.height / (orderData.is34 ? 133.333333 : orderData.isSku ? 100 : 100)
            context.drawImage(
              whimg,
              wb * orderData.watermark.left,
              hb * orderData.watermark.top,
              wb * orderData.watermark.width,
              hb * orderData.watermark.height
            )

            let canvas2 = document.createElement("canvas")
            canvas2.width = canvas.width;
            canvas2.height = canvas.height;
            let ctx2: any = canvas2.getContext("2d");
            let imageData = context.getImageData(0, 0, canvas.width, canvas.height);
            let imgData2 = dealImageData(imageData);
            ctx2.putImageData(imgData2, 0, 0);
            orderData.mergeurl = canvas2.toDataURL(imagetype, 1)
            // orderData.mergeurl = canvas.toDataURL("image/jpeg", 1)
            // console.log('orderData.mergeurl ', orderData.mergeurl)
            resolve(orderData)

          }
          return
        }
        orderData.mergeurl = ''
        orderData.isNoSet = true
        resolve(orderData)
        return
      }
      img = new Image()
      img.setAttribute("crossOrigin", "Anonymous")
      img.src = orderData.url // + '?time=' + new Date().valueOf()

      // if (ister) {
      //   imagetype = 'image/png'
      // }
      // console.log('imagetype', imagetype)
      whimg = new Image()
      whimg.setAttribute("crossOrigin", "Anonymous")

      whimg.src = orderData.watermark.url
      // console.log('whimg.src00', whimg.src)
      // console.log('orderData.watermark.url ', orderData.watermark.url )
      // console.image(orderData.watermark.url)
      lodinImagelist.push(
        new Promise((resolvea) => {
          img.onload = resolvea
        })
      )
      if (orderData.watermark.url) {
        lodinImagelist.push(
          new Promise((resolvea) => {
            whimg.onload = resolvea
          }))
      }
      Promise.all(lodinImagelist).then(() => {
        let canvas = document.createElement("canvas")
        let context: any = canvas.getContext("2d")
        canvas.width = 800
        canvas.height = 800
        context.drawImage(img, 0, 0, canvas.width, canvas.height)
        // 存在即合并
        if (orderData.watermark.url) {
          const wb = canvas.width / 100
          const hb = canvas.height / 100
          // 将第二张图片绘制到右侧位置
          context.drawImage(
            whimg,
            wb * orderData.watermark.left,
            hb * orderData.watermark.top,
            wb * orderData.watermark.width,
            hb * orderData.watermark.height
          )
        }

        // 对图片微调像素
        let canvas2 = document.createElement("canvas")
        canvas2.width = canvas.width;
        canvas2.height = canvas.height;
        let ctx2: any = canvas2.getContext("2d");
        let imageData = context.getImageData(0, 0, canvas.width, canvas.height);
        let imgData2 = dealImageData(imageData);
        ctx2.putImageData(imgData2, 0, 0);
        if (cherTypeIn == 1) {
          ctx2.fillStyle = 'rgba(255, 255, 255, 0.2)'; // 设置文字颜色及透明度
          ctx2.font = '20px Arial'; // 设置文字样式
          ctx2.fillText(generateRandomString(3), 755, 795, 100, 100);
        }
        if (cherTypeIn == 2 && orderData.worderker) {
          ctx2.fillStyle = 'rgba(255, 255, 255, 0.3)'; // 设置文字颜色及透明度
          ctx2.font = '20px Arial'; // 设置文字样式
          ctx2.fillText(generateRandomString(3), 755, 795, 100, 100);
        }

        // let mergeurl = canvas.toDataURL("image/jpeg", 1)
        orderData.mergeurl = canvas2.toDataURL(imagetype, 1)
        // console.log('orderData.mergeurl ', orderData.mergeurl)
        resolve(orderData)

      })

    })
  }


}


// 判断图片是否为透明图
export function isTransparentImage(src) {
  // console.log('src00114477/*//*//*/', src)
  return new Promise((resolve, reject) => {
    if (!src) {
      resolve(false)
      return
    }


    let imgIster = new Image()
    imgIster.setAttribute("crossOrigin", "Anonymous")

    imgIster.src = src
    imgIster.onload = function () {
      let canvasTure = document.createElement('canvas');
      let ctxTure = canvasTure.getContext('2d');
      canvasTure.width = imgIster.width;
      canvasTure.height = imgIster.height;
      ctxTure.drawImage(imgIster, 0, 0);
      let imageDataTure = ctxTure.getImageData(0, 0, canvasTure.width, canvasTure.height);
      let dataTure = imageDataTure.data;

      let affUer = 0
      for (var i = 0; i < dataTure.length; i += 4) {
        if (dataTure[i + 3] < 255) { // 如果发现透明像素
          affUer++
          if (affUer > 20) {
            resolve(true); // 图片是透明的
            return;
          }
        }
      }
      resolve(false); // 图片不是透明的
    }

  })
}


export function dealImageData(imageData) {
  const miyer = Math.floor(Math.random() * 5)
  const clearLierw: any = []

  let d = imageData.data;
  for (let i = 0; i < 20; i++) {
    clearLierw.push(Math.floor(Math.random() * d.length))
  }
  for (let i = 0; i < d.length; i += 4) {
    if (d[i] < 245) {
      d[i] = d[i] + miyer;
    }
    if (d[i + 1] < 245) {
      d[i + 1] = d[i + 1] + miyer;
    }
    if (d[i + 2] < 245) {
      d[i + 2] = d[i + 2] + miyer;
    }
    if (clearLierw.includes(i)) {
      d[i + 3] = 185
    }
  }
  return imageData;
}
// async function upBefroDater(upImages) {
//   const proAll = upImages.map(res => {
//     return updataImage(res)
//   })
//   const prodata = await Promise.all(proAll)
//   // console.log('prodataprodataprodata', prodata)
//   return prodata
// }

// // 上传图片
// async function updataImage(basedataOr) {
//   const { userShopId } = store.getState().jinritemaiShops
//   const basedata = JSON.parse(JSON.stringify(basedataOr))
//   // const ossKetData = await getOssKeyData()
//   // console.log('basedatabasedata', basedata)
//   const upImageData = basedata.list.map((fileb, i) => {
//     if (fileb.isNoSet) {
//       // console.log('不需要上传的文件')
//       return Promise.resolve({
//         url: fileb.mergeurl,
//         isNoupLoads: true
//       })
//     }
//     const bytes = window.atob(fileb.mergeurl.split(",")[1])
//     // console.log('bytes123456789', bytes)
//     let ab = new ArrayBuffer(bytes.length)
//     let ia = new Uint8Array(ab)
//     for (let i = 0; i < bytes.length; i++) {
//       ia[i] = bytes.charCodeAt(i)
//     }
//     let blob = new Blob([ab], { type: "image/jpeg" })
//     return upFileToOss({
//       file: blob,
//       fileName: `${userShopId || '公共'}/${md5(fileb.mergeurl)}.jpg`,
//     })
//   })

//   return await Promise.all(upImageData)
// }


export async function upBefroDaterNew(upImages) {
  // console.log('upImages', upImages)
  const proAll = upImages.map(res => {
    // console.log('res', res)
    return updataImageNew(res)
  })
  const prodata = await Promise.all(proAll)
  // console.log('prodataprodataprodata', prodata)
  return prodata
}

// 上传图片
export async function updataImageNew(basedataOr) {
  // console.log('basedataOr', basedataOr)
  // const { userShopId } = store.getState().jinritemaiShops
  const basedata = JSON.parse(JSON.stringify(basedataOr))
  // const ossKetData = await getOssKeyData()
  // console.log('basedatabasedata', basedata)
  const upImageData = basedata.list.map((fileb, i) => {
    if (fileb.isNoSet) {
      // console.log('不需要上传的文件', fileb.mergeurl)
      return Promise.resolve({
        url: fileb.mergeurl,
        isNoupLoads: true
      })
    }
    // const bytes = window.atob(fileb.mergeurl.split(",")[1])
    // let ab = new ArrayBuffer(bytes.length)
    // let ia = new Uint8Array(ab)
    // for (let i = 0; i < bytes.length; i++) {
    //   ia[i] = bytes.charCodeAt(i)
    // }
    // let blob = new Blob([ab], { type: "image/jpeg" })
    // var file = new File([blob], `${md5(fileb.mergeurl)}.jpeg`, {
    //   type: 'image/jpeg',
    // });
    return upImageItemFunc(fileb.mergeurl)
    // // 创建FormData对象并添加File对象
    // var formData = new FormData();
    // formData.append('image[0]', file);
    // return upDataImageNewApi(formData)
    // return upFileToOss({
    //   file: blob,
    //   fileName: `${userShopId || '公共'}/${md5(fileb.mergeurl)}.png`,
    // })
  })

  return await Promise.all(upImageData)
}

export async function upImageItemFunc(mergeurl) {
  // console.log('mergeurl993663325588', mergeurl)
  // const literinter = mergeurl.split(",")[1]
  const type = mergeurl.split(",")[0].split("/")[1].split(";")[0]
  // console.log('type000333', type)
  const bytes = window.atob(mergeurl.split(",")[1])
  let ab = new ArrayBuffer(bytes.length)
  let ia = new Uint8Array(ab)
  for (let i = 0; i < bytes.length; i++) {
    ia[i] = bytes.charCodeAt(i)
  }
  let blob = new Blob([ab], { type: `image/${type}` })
  var file = new File([blob], `${md5(mergeurl)}.${type}`, {
    type: `image/${type}`,
  });

  // 创建FormData对象并添加File对象
  var formData = new FormData();
  formData.append('image[0]', file);
  return upDataImageNewApi(formData)
}



export async function getProductUpdateRuleData(category_id) {
  const res = await getProductUpdateRule(category_id)
  return res
}

export function generateRandomString(length) {
  let result = '';
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  const charactersLength = characters.length;

  for (let i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength));
  }

  return result;
}

export function urlToBase64(url) {
  return new Promise((resolve, reject) => {
    let xhr = new XMLHttpRequest();
    xhr.open('GET', url);
    xhr.responseType = 'blob';
    xhr.onload = function () {
      if (xhr.status === 200) {
        let reader = new FileReader();
        reader.onloadend = function () {
          resolve(reader.result);
        };
        reader.onerror = reject;
        reader.readAsDataURL(xhr.response);
      } else {
        reject(xhr.statusText);
      }
    };
    xhr.onerror = reject;
    xhr.send();
  });
}

// 创建任务ID
export function createTaskId() {
  return generateRandomString(8) +
    String(Date.now()).substr(5) +
    String(Math.random()).substr(2, 4)
}



export async function fengeDeteailImage(list, num) {
  // console.log('开始分割', list, num)
  let dearNum = num > 50 ? 50 : num
  let imageList = []
  try {
    imageList = JSON.parse(JSON.stringify(list)).map(res => res.url)
  } catch (error) {
    throw new Error("err", error);

  }
  const imageOnloadPromise = []
  imageList.forEach((item, index) => {
    let img = new Image()
    img.setAttribute("crossOrigin", "Anonymous")
    img.src = item
    imageOnloadPromise.push(new Promise((resolve) => {
      img.onload = () => {
        resolve(img)
      }
    }))
  })
  const res = await Promise.all(imageOnloadPromise)
  const canvasWidth = 600
  const canvas = document.createElement('canvas')
  let canvasHeight = 0
  const ctx = canvas.getContext('2d')


  res.forEach((item) => {
    const imageWidth = item.naturalWidth
    const imageHeight = item.naturalHeight
    canvasHeight = canvasHeight + Number(((canvasWidth / imageWidth) * imageHeight).toFixed(2))
  })

  canvas.width = canvasWidth
  canvas.height = canvasHeight
  let potionY = 0
  res.forEach((item, index) => {
    const imageWidth = item.naturalWidth
    const imageHeight = item.naturalHeight
    const drawY = Number(((canvasWidth / imageWidth) * imageHeight).toFixed(2))

    ctx.drawImage(item, 0, potionY, canvasWidth, drawY)
    potionY = potionY + drawY
  })
  const base64 = canvas.toDataURL('image/jpeg', 1)

  // 裁切canvas图片

  let dearHeight = canvasHeight / dearNum
  let dearCanvas = document.createElement('canvas')
  let dearCtx = dearCanvas.getContext('2d')
  dearCanvas.width = canvasWidth
  dearCanvas.height = dearHeight
  const dorwUrls = []
  for (let i = 0; i < dearNum; i++) {
    dearCtx.drawImage(canvas, 0, dearHeight * i, canvasWidth, dearHeight, 0, 0, canvasWidth, dearHeight)
    let liter = num >= 5 ? 1 : 0.6
    if (num == 1) {
      liter = 0.4
    }
    const dearBase64 = dearCanvas.toDataURL('image/jpeg', liter)
    dorwUrls.push(dearBase64)
  }
  // console.log('dorwUrls', dorwUrls)
  return dorwUrls

}

// 压缩图片
export function compressImage(imageUrl, quality, width?, height?) {

  return new Promise(async (resolve, reject) => {
    let imagetype = 'image/jpeg'
    const ister = await isTransparentImage(imageUrl)
    if (ister) {
      imagetype = 'image/png'
    }
    let imgIster = new Image()
    imgIster.setAttribute("crossOrigin", "Anonymous")
    imgIster.src = imageUrl
    imgIster.onload = () => {
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      canvas.width = width || imgIster.width;
      canvas.height = height || imgIster.height;
      ctx.drawImage(imgIster, 0, 0, canvas.width, canvas.height);
      const compressedImage = canvas.toDataURL(imagetype, quality);
      // console.log('compressedImage', compressedImage)
      resolve(compressedImage);
    };
    imgIster.onerror = (error) => {
      console.log('error', error)
      reject(error);
    };
  });

}